
/* eslint-disable */
import * as d3 from "d3"
import moment from "moment"

//1、新建svg画布
const height = 500, width: 1000, marginBottom = 40

const formateDay = (date) => {
    console.log(date)
    return date.getDate() + "号"
}

let svg = d3.create("svg").attr("width", width).attr("height", height).attr("class", "box")
document.body.appendChild(svg.node())

const fontSize = 16
const startTime = "2023-12-1"
const endTime = "2024-2-1"
const totalDayCount = moment(endTime).diff(moment(startTime), 'day') + 1
const extendDay = 10
const everyDay = 10
const step = (fontSize / 10) * 40
let showStartTime = moment(startTime).add("day", -1 * extendDay).toDate()
let showEndTime = moment(endTime).add("day", extendDay).toDate()


console.log("endTime", moment(showEndTime).format("YYYY-MM-DD"))

svg.attr("width", step * totalDayCount)

let monthMap = computeMothMap(showStartTime, showEndTime)
let tickValues = computeTickValues(everyDay, monthMap);

let tickValuesdesc = tickValues.map(s => {
    return moment(s).format("YYYY-MM-DD")
})

console.log("tickValues", tickValuesdesc)


const xStart = 20, xEnd = Number(svg.attr("width")) - xStart * 2
//2、创建一个X坐标轴
const xScale = d3.scaleTime([showStartTime, showEndTime], [xStart, xEnd]);
// x.ticks(d3.utcMinute.every(24 *  ));
const dayAxis = d3.axisTop(xScale).tickValues(tickValues)
    .tickFormat(d => moment(d).format("DD"))

const dx = svg.append("g")
    .attr("class", "x-axis")
    .attr("transform", `translate(0,${height - 100})`)
    .call(dayAxis);

const tickOffsets = []

const positionComptedFn = dx.node().__axis

dx.selectAll(".tick").each(function (d, index, nodes) {
    let nextData = nodes[index + 1]?.__data__ || showEndTime
    let distance = positionComptedFn(nextData) - positionComptedFn(d)
    distance *= 0.5

    d3.select(this).select("text").attr("text-anchor", "middle").attr("transform", `translate(${distance},0)`).text((d) => {
        if (distance === 0) return ""

        let d0 = moment(d).format("DD")
        let d1 = moment(nextData).add("day", -1).format("DD")
        if (d0 === d1) return d0 + '日'

        return `${d0}日 ~ ${d1}日`
    })

})


dx.selectAll(".tick").each(function (d, index, obj) {
    tickOffsets.push(positionComptedFn(d))
})

const colorScale = d3.scaleOrdinal(d3.schemeCategory10)

drawMonthXAxis(monthMap)

function computeMothMap(begin, end) {
    let mCount = moment(end).startOf("month").diff(moment(begin).startOf("month"), "month");
    const monthMap = {}

    let startMonth = moment(begin).format("YYYY-MM")
    let endMonth = moment(end).format("YYYY-MM")

    for (let i = 0; i <= mCount; i++) {
        let cm = moment(begin).add('month', i).format("YYYY-MM");

        let mStartDay = moment(cm).startOf('month');//当前月开始时间
        let mEndDay = moment(cm).endOf('month');

        if (cm === startMonth && mStartDay.isBefore(moment(begin))) {
            mStartDay = moment(begin)
        }

        if (cm === endMonth && moment(end).isBefore(mEndDay)) {
            mEndDay = moment(end)
        }

        monthMap[cm] = {
            startDay: mStartDay,
            endDay: mEndDay
        }
    }

    return monthMap
}


function drawMonthXAxis(monthMap) {
    for (const key in monthMap) {
        if (Object.hasOwnProperty.call(monthMap, key)) {
            const { startDay, endDay } = monthMap[key]
            drawMonthRect(startDay, endDay)
        }
    }

}

function drawMonthRect(monthStart, monthEnd) {
    const monthStr = moment(monthStart).format("YYYY-MM")
    const monthIndex = Number(moment(monthStart).format("MM"))
    const monthColor = colorScale(monthIndex)

    const rectX0 = positionComptedFn(moment(monthStart).toDate())
    const rectX1 = positionComptedFn(moment(monthEnd).toDate())
    const rectW = rectX1 - rectX0
    const rectH = 30

    const centerX = (rectX1 - rectX0) * 0.5 + rectX0

    const mx = svg.append("g")
        .attr("class", "month-axis")
        .attr("transform", `translate(0,${height - height + rectH})`)
        .attr("fill", "orange")

    svg.select(".month-axis")
        .append("rect")
        .attr("x", rectX0)
        .attr("y", 0)
        .attr("width", rectW)
        .attr("height", rectH)
        .attr("fill", monthColor)

    svg.select(".month-axis")
        .append("text")
        .attr("text-anchor", "middle")
        .attr("class", "month-text")
        .text((d, index, node) => {
            return monthStr
        })
        .attr('fill', 'blue')
        .attr('x', centerX)
        .attr('y', rectH * 0.5)
        .style('font-size', '20px')
        .attr('dy', 8)

}

function computeTickValues(everyDay, monthMap) {
    let ticks = []
    for (const month in monthMap) {
        if (Object.hasOwnProperty.call(monthMap, month)) {
            const { startDay, endDay } = monthMap[month];

            let s = Number(moment(startDay).format("DD"))
            let e = Number(moment(endDay).format("DD"))

            for (let i = s; i <= e; i += everyDay) {
                let markDay = i
                if (markDay > e) {
                    markDay = e
                }

                let atTime = moment(startDay).add("day", markDay - s)
                ticks.push(atTime)
            }

        }
    }

    return ticks

}
